package cn.cvs.service;

import cn.cvs.dao.StorageRecordMapper;
import cn.cvs.dao.SupplierMapper;
import cn.cvs.pojo.Supplier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;

@Service
public class SupplierServiceImpl implements SupplierService {
    @Resource
    private SupplierMapper supplierMapper;
    @Resource
    private StorageRecordMapper storageRecordMapper;

    public SupplierServiceImpl() {
    }

    public List<Supplier> getList(String supName, String supCode, int pageIndex, int pageSize) throws Exception {
        int pageBegin = (pageIndex - 1) * pageSize;
        return this.supplierMapper.selectList(supName, supCode, pageBegin, pageSize);
    }

    public int getCount(String supName, String supCode) throws Exception {
        return this.supplierMapper.selectCount(supName, supCode);
    }

    public boolean add(Supplier supplier) throws Exception {
        boolean flag = false;
        supplier.setCreatedTime(new Date());
        if (this.supplierMapper.add(supplier) > 0) {
            flag = true;
        }

        return flag;
    }

    public List<Supplier> getList() throws Exception {
        return this.supplierMapper.selectSimpleList();
    }

    public Supplier getById(Integer id) throws Exception {
        return this.supplierMapper.selectById(id);
    }

    public boolean update(Supplier supplier) throws Exception {
        boolean flag = false;
        supplier.setUpdatedTime(new Date());
        if (this.supplierMapper.update(supplier) > 0) {
            flag = true;
        }

        return flag;
    }

    public boolean deleteById(Integer id) throws Exception {
        boolean flag = true;
        int billCount = this.storageRecordMapper.selectCountBySupplierId(id);
        if (billCount > 0) {
            this.storageRecordMapper.deleteBySupplierId(id);
        }

        Supplier supplier = this.supplierMapper.selectById(id);
        File file;
        if (supplier.getCompanyLicPicPath() != null && !supplier.getCompanyLicPicPath().equals("")) {
            file = new File(supplier.getCompanyLicPicPath());
            if (file.exists()) {
                flag = file.delete();
            }
        }

        if (flag && supplier.getOrgCodePicPath() != null && !supplier.getOrgCodePicPath().equals("")) {
            file = new File(supplier.getOrgCodePicPath());
            if (file.exists()) {
                flag = file.delete();
            }
        }

        if (!flag) {
            throw new Exception();
        } else {
            this.supplierMapper.deleteById(id);
            return flag;
        }
    }
}

